package top.lingkang.finalsession.javax;

import top.lingkang.finalsession.core.FinalSessionHandler;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * javax.servlet.http 的实现
 *
 * @author lingkang
 * Created by 2024/3/10
 */
public class FinalSessionHandlerCookie implements FinalSessionHandler<HttpServletRequest, HttpServletResponse> {

    @Override
    public String getSessionId(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null)
            return null;
        for (Cookie cookie : cookies) {
            if (name.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }
        return null;
    }

    @Override
    public void setSessionId(HttpServletResponse response, String name, String value) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}
